import '../scss/Tab.scss'
import nav from '../components/Tab/Nav'
import page from '../components/Tab/page'
import data from '../data/index'
export default class Tab {
    constructor(app) {
        this.app = app
        this.oTab = document.createElement('div')
        this.oTab.className = 'tab J_tab'
        this.navComponent = nav()
        this.pageComponent = page()
        this.currentIndex = 0
        this.htmlCache = {}
    }
    init() {
        this.render()
        this.getElements()
        this.navComponent.bindEvent(this.onNavClick.bind(this))
    }
    getElements() {
        this.oNavItems = this.oTab.getElementsByClassName('nav-item')
        this.oPage = this.oTab.getElementsByClassName('page')[0]
    }
    render() {
        const tpl = this.pageComponent.tpl(data[this.currentIndex])
        this.oTab.appendChild(this.navComponent.tpl(data))
        this.oTab.appendChild(tpl.oPage)
        this.htmlCache[this.currentIndex] = tpl.pageHtml

        this.app.appendChild(this.oTab)
    }
    onNavClick(ev) {
        const e = ev || window.event,
            tar = e.target || e.srcElement,
            className = tar.className
        className === 'nav-item' && this.changePage(tar)

    }
    changePage(target) {
        this.oNavItems[this.currentIndex].className = 'nav-item'
        this.currentIndex = [].indexOf.call(this.oNavItems, target)
        this.oNavItems[this.currentIndex].className += ' current'
        this.oPage.innerHTML = this.renderHtml(data,this.currentIndex)
    }
    renderHtml(_data,index) {
        if(!this.htmlCache[index]){
            this.htmlCache[index] = this.pageComponent.renderPage(_data[this.currentIndex])
        }
        return this.htmlCache[index]
    }
}